
from flask import (
    Blueprint, request, jsonify,make_response
)
import dashscope
from http import HTTPStatus
from dashscope import Generation
from dashscope.api_entities.dashscope_response import Role


bp = Blueprint('ai', __name__)

dashscope.api_key="sk-50e1a147d8c5437fa765a57886acd360"

@bp.route('/ai',methods=('POST',), endpoint='getAiAnswer')
def getAiAnswer():
    #获取前端message
    messages = request.json

    try:
       res = conversation_with_messages(messages)
    except Exception as e:
        return make_response(jsonify({
            "msg": "请求错误",
            "code": 500
        }))
    return jsonify(res)

def conversation_with_messages(messages):
    response = dashscope.Generation.call(
        model= 'qwen-max-longcontext',
        messages = messages,
        top_p = 0.5,
        repetition_penalty = 1.2,
        enable_search = True,
        stream = False,
        incremental_output = False,
        result_format='message',  # set the result to be "message" format.
    )
    return response

